import serial
from PyQt5.QtCore import QThread
from serial.serialutil import SerialException

from app.ui.tool.ais_serial_tool.serial_thread import SerialWorker


class SerialHandler:
    def __init__(self, port, baud_rate):
        self.thread = QThread()
        self.worker = SerialWorker(port, baud_rate)

        # 将worker移动到线程中
        self.worker.moveToThread(self.thread)
        # 连接信号与槽
        self.thread.started.connect(self.worker.run)
        self.worker.data_received.connect(self.on_data_received)
        self.worker.error_occurred.connect(self.on_error)

        self.thread.finished.connect(self.worker.deleteLater)
        self.worker.error_occurred.connect(self.close)

    def open(self):
        self.thread.start()

    def close(self):
        self.worker.stop()
        self.thread.quit()
        self.thread.wait()

    def on_data_received(self, data):
        print(data)

    def on_error(self, error_msg):
        print(error_msg)
        self.close()
